<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AJAX 返回数据问题</title>
</head>
<body>
  <script>

    // 封装者
    // =============================

    function ajax (method, url, params, done) {
      method = method.toUpperCase()
      var xhr = new XMLHttpRequest()

      if (typeof params === 'object') {
        var tempArr = []
        for (var key in params) {
          var value = params[key]
          tempArr.push(key + '=' + value)
        }
        params = tempArr.join('&')
      }

      if (method === 'GET') {
        url += '?' + params
      }

      xhr.open(method, url, false)

      var data = null
      if (method === 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        data = params
      }

      xhr.onreadystatechange = function () {
        if (this.readyState !== 4) return
        // 不应该在封装的函数中主观的处理响应结果
        // console.log(this.responseText)
        // 你说我太主观，那么你告诉我应该做什么
        done(this.responseText)
      }

      xhr.send(data)
    }

    // 调用者
    // ============================

    var onDone = function (res) {
      console.log('hahahahaha')
      console.log('hohohohoho')
      console.log(res)
      console.log('做完了')
    }

    ajax('get', 'time.php', {}, onDone)

  </script>
</body>
</html>
